#include "colorkey.h"
#include <SDL.h>
#include <SDL_image.h>

void initTexture(Texture_t *pTexture, SDL_Renderer *renderer, const char* path){
    if(pTexture){
        pTexture->imgHeight = 0;
        pTexture->imgWidth = 0;
        pTexture->texture = NULL;
        pTexture->renderer = renderer;
        pTexture->imgPath = path;
    }
}

void loadFromFile(Texture_t *pTexture){
    SDL_Surface *surface = IMG_Load(pTexture->imgPath);
    if(!surface){
        printf("Load file %s failed: %s\n", pTexture->imgPath, IMG_GetError());
    }else{
        SDL_SetColorKey(surface, SDL_TRUE, SDL_MapRGB(surface->format, 0, 0xff, 0xff));
        pTexture->texture = SDL_CreateTextureFromSurface(pTexture->renderer, surface);
        if(!pTexture->texture){
            printf("Create texture failed: %s\n", SDL_GetError());
        }
        pTexture->imgWidth = surface->w;
        pTexture->imgHeight = surface->h;
        SDL_FreeSurface(surface);
    }
}

void renderTexture(Texture_t *pTexture, int x, int y){
    SDL_Rect rect = {x, y, pTexture->imgWidth, pTexture->imgHeight};
    SDL_RenderCopy(pTexture->renderer, pTexture->texture, NULL, &rect);
}

void freeTexture(Texture_t *pTexture){
    if(pTexture){
        if(pTexture->texture){
            SDL_DestroyTexture(pTexture->texture);
            pTexture->texture = NULL;
            pTexture->imgHeight = 0;
            pTexture->imgWidth = 0;
        }
    }
}
